<?php 

namespace pmvc\mvc\security\basic;

use pmvc\data\DataSource;

/**
 * <p>
 * Basic implementation of the {@link UserDao} interface that
 * requires a {@link DataSource}, a sql query and an optional
 * roleDelimiter to be set.  The sql query is executed using
 * the {@link DataSource#querySingle()} method passing it the
 * provided query as the first argument and the user provided
 * username as the second argument.  The sql query must return
 * a tuple in the following format (but in any order):
 * </p>
 * <p>
 * <pre>&lt;id, roles, username, password, isPasswordEncoded&gt;</pre>
 * <ul>
 * 	<li>id - any unique identifier for the user</li>
 * 	<li>roles - a list of roles delimited by the provided
 * {@code roleDelimiter}</li>
 * 	<li>username - the username</li>
 * 	<li>password - the password</li>
 * 	<li>isPasswordEncoded - a boolean indicator as to whether or not
 * the user's password is encoded</li>
 * </ul>
 * </p>
 * <p>
 * example:
 * <pre>
 * select
 * 	id, roles, emailAddress as username, passwordHash as password, 1 as isPasswordEncoded
 * from
 * 	userAccounts
 * where
 * 	emailAddress={0};
 * </pre>
 * </p>
 */
class DataSourceUserDao
	implements UserDao {

	private $dataSource;
	private $sqlQuery;
	private $roleDelimiter = ",";

	public function getUser(BasicAuthentication $authentication) {
		$result = $this->dataSource->querySingle(
			$this->sqlQuery, $authentication->getUsername());
		if (!$result) {
			return NULL;
		}
		return new BasicUser(
			explode($this->roleDelimiter, $result->roles), 
			$result->id,
			$result->username,
			$result->password, 
			$result->isPasswordEncoded,
			(Array)$result);
	}

	public function setDataSource(DataSource $dataSource) {
		$this->dataSource = $dataSource;
	}

	public function setSqlQuery($sqlQuery) {
		$this->sqlQuery = $sqlQuery;
	}

	public function setRoleDelimiter($roleDelimiter) {
		$this->roleDelimiter = $roleDelimiter;
	}

}

?>